package com.businesscard.system.service.impl;

import com.businesscard.system.entity.BusinessCard;
import com.businesscard.system.mapper.BusinessCardMapper;
import com.businesscard.system.service.BusinessCardService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 名片服务实现
 */
@Service
public class BusinessCardServiceImpl implements BusinessCardService {

    @Autowired
    private BusinessCardMapper cardMapper;

    @Override
    public boolean createCard(BusinessCard card) {
        return cardMapper.insertCard(card) > 0;
    }

    @Override
    @Transactional
    public boolean batchCreateCards(List<BusinessCard> cards) {
        return cardMapper.batchInsertCards(cards) > 0;
    }

    @Override
    public boolean updateCard(BusinessCard card) {
        return cardMapper.updateCard(card) > 0;
    }

    @Override
    public BusinessCard getCardById(Integer id) {
        return cardMapper.selectCardById(id);
    }

    @Override
    public List<BusinessCard> getCardsByFolderId(Integer folderId) {
        return cardMapper.selectCardsByFolderId(folderId);
    }

    @Override
    public List<BusinessCard> getDeletedCardsByFolderId(Integer folderId) {
        return cardMapper.selectDeletedCardsByFolderId(folderId);
    }

    @Override
    public boolean deleteCard(Integer id) {
        return cardMapper.logicalDeleteCard(id) > 0;
    }

    @Override
    public boolean restoreCard(Integer id) {
        return cardMapper.restoreCard(id) > 0;
    }

    @Override
    public boolean removeCard(Integer id) {
        return cardMapper.deleteCard(id) > 0;
    }

    @Override
    public List<BusinessCard> searchCards(Map<String, Object> params) {
        return cardMapper.searchCards(params);
    }

    @Override
    @Transactional
    public boolean batchUpdateCards(List<Integer> cardIds, String fieldName, String newValue) {
        return cardMapper.batchUpdateCards(cardIds, fieldName, newValue) > 0;
    }

    @Override
    @Transactional
    public Map<String, Object> importCards(MultipartFile file, Integer folderId) {
        Map<String, Object> result = new HashMap<>();
        List<BusinessCard> successList = new ArrayList<>();
        List<Map<String, Object>> failList = new ArrayList<>();
        
        try (InputStream is = file.getInputStream()) {
            Workbook workbook = WorkbookFactory.create(is);
            Sheet sheet = workbook.getSheetAt(0);
            
            // 跳过表头
            int rowStart = 1;
            int rowEnd = sheet.getLastRowNum();
            
            for (int rowNum = rowStart; rowNum <= rowEnd; rowNum++) {
                Row row = sheet.getRow(rowNum);
                
                try {
                    if (row == null) {
                        continue;
                    }
                    
                    BusinessCard card = new BusinessCard();
                    card.setFolderId(folderId);
                    
                    // 根据Excel文件格式解析名片信息
                    card.setName(getCellValueAsString(row.getCell(0)));
                    card.setGender(getCellValueAsString(row.getCell(1)));
                    card.setPhone(getCellValueAsString(row.getCell(2)));
                    card.setOrganization(getCellValueAsString(row.getCell(3)));
                    card.setPosition(getCellValueAsString(row.getCell(4)));
                    card.setAddress(getCellValueAsString(row.getCell(5)));
                    card.setEmail(getCellValueAsString(row.getCell(6)));
                    card.setRemark(getCellValueAsString(row.getCell(7)));
                    
                    // 验证必填字段
                    if (card.getName() == null || card.getName().trim().isEmpty()) {
                        Map<String, Object> failRecord = new HashMap<>();
                        failRecord.put("rowNum", rowNum + 1);
                        failRecord.put("reason", "姓名不能为空");
                        failList.add(failRecord);
                        continue;
                    }
                    
                    successList.add(card);
                } catch (Exception e) {
                    Map<String, Object> failRecord = new HashMap<>();
                    failRecord.put("rowNum", rowNum + 1);
                    failRecord.put("reason", "解析数据异常: " + e.getMessage());
                    failList.add(failRecord);
                }
            }
            
            // 批量插入成功解析的名片
            if (!successList.isEmpty()) {
                cardMapper.batchInsertCards(successList);
            }
            
            result.put("success", successList.size());
            result.put("fail", failList);
            
            return result;
        } catch (IOException e) {
            throw new RuntimeException("解析Excel文件失败", e);
        }
    }

    @Override
    public byte[] exportCards(Integer folderId) {
        List<BusinessCard> cards = cardMapper.selectCardsByFolderId(folderId);
        
        try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Sheet sheet = workbook.createSheet("名片信息");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"姓名", "性别", "联系电话", "机构名称", "职务", "地址", "电子邮箱", "备注"};
            
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.autoSizeColumn(i);
            }
            
            // 填充数据
            int rowNum = 1;
            for (BusinessCard card : cards) {
                Row row = sheet.createRow(rowNum++);
                
                row.createCell(0).setCellValue(card.getName() != null ? card.getName() : "");
                row.createCell(1).setCellValue(card.getGender() != null ? card.getGender() : "");
                row.createCell(2).setCellValue(card.getPhone() != null ? card.getPhone() : "");
                row.createCell(3).setCellValue(card.getOrganization() != null ? card.getOrganization() : "");
                row.createCell(4).setCellValue(card.getPosition() != null ? card.getPosition() : "");
                row.createCell(5).setCellValue(card.getAddress() != null ? card.getAddress() : "");
                row.createCell(6).setCellValue(card.getEmail() != null ? card.getEmail() : "");
                row.createCell(7).setCellValue(card.getRemark() != null ? card.getRemark() : "");
            }
            
            // 调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            workbook.write(outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("导出Excel文件失败", e);
        }
    }
    
    @Override
    public byte[] exportCardsBySearchParams(Map<String, Object> params) {
        List<BusinessCard> cards = cardMapper.searchCards(params);
        
        try (Workbook workbook = new XSSFWorkbook(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            Sheet sheet = workbook.createSheet("名片信息");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"姓名", "性别", "联系电话", "机构名称", "职务", "地址", "电子邮箱", "备注"};
            
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
                sheet.autoSizeColumn(i);
            }
            
            // 填充数据
            int rowNum = 1;
            for (BusinessCard card : cards) {
                Row row = sheet.createRow(rowNum++);
                
                row.createCell(0).setCellValue(card.getName() != null ? card.getName() : "");
                row.createCell(1).setCellValue(card.getGender() != null ? card.getGender() : "");
                row.createCell(2).setCellValue(card.getPhone() != null ? card.getPhone() : "");
                row.createCell(3).setCellValue(card.getOrganization() != null ? card.getOrganization() : "");
                row.createCell(4).setCellValue(card.getPosition() != null ? card.getPosition() : "");
                row.createCell(5).setCellValue(card.getAddress() != null ? card.getAddress() : "");
                row.createCell(6).setCellValue(card.getEmail() != null ? card.getEmail() : "");
                row.createCell(7).setCellValue(card.getRemark() != null ? card.getRemark() : "");
            }
            
            // 调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            workbook.write(outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("导出Excel文件失败", e);
        }
    }
    
    // 辅助方法：获取单元格的字符串值
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return null;
        }
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    return cell.getDateCellValue().toString();
                }
                return String.valueOf((long) cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            case FORMULA:
                return cell.getCellFormula();
            default:
                return null;
        }
    }
} 